import { defineStore } from 'pinia'
import { getDailySummary, getWeeklySummary, getMonthlySummary } from '@/api/summaries'

export type SummaryType = 'daily' | 'weekly' | 'monthly' | 'manual'

export interface Summary {
  id: number
  user_id: number
  type: SummaryType
  content: string
  period_start?: string
  period_end?: string
  created_at: string
  updated_at?: string
  entry_id?: number
  tokens_used?: number
  model?: string
}

interface State {
  list: Summary[]
  dailySummaries: Summary[]
  weeklySummaries: Summary[]
  monthlySummaries: Summary[]
  currentSummary: Summary | null
  loading: boolean
  loaded: boolean
  error: string | null
}

function normalizeSummary(data: any): Summary {
  const typeRaw = data?.type ?? 'daily'
  const type = (typeof typeRaw === 'string' ? typeRaw.toLowerCase() : String(typeRaw)).trim() as SummaryType
  return {
    id: data?.id || data?.summary_id || 0,
    user_id: data?.owner_id || data?.ownerId || data?.user_id || data?.userId || 0,
    type,
    content: data?.content || data?.summary_content || '',
    period_start: data?.period_start || data?.periodStart || data?.date || data?.week || data?.month || '',
    period_end: data?.period_end || data?.periodEnd || '',
    created_at: data?.created_at || data?.createdAt || new Date().toISOString(),
    updated_at: data?.updated_at || data?.updatedAt || '',
    entry_id: data?.entry_id || data?.entryId,
    tokens_used: data?.tokens_used || data?.tokensUsed,
    model: data?.model,
  }
}

export const useSummariesStore = defineStore('summaries', {
  state: (): State => ({
    list: [],
    dailySummaries: [],
    weeklySummaries: [],
    monthlySummaries: [],
    currentSummary: null,
    loading: false,
    loaded: false,
    error: null,
  }),
  persist: {
    key: 'mirrorforest-summaries-store',
    storage: window.localStorage,
    paths: ['list', 'dailySummaries', 'weeklySummaries', 'monthlySummaries', 'loaded'],
  } as any,
  getters: {
    // 根据类型获取摘要列表
    byType: (state) => (type: SummaryType) => {
      return state.list.filter(s => s.type === type)
    },
    // 根据ID获取摘要
    byId: (state) => (id: number | string) => {
      return state.list.find(s => s.id === Number(id))
    },
    // 获取最新的每日摘要
    latestDaily: (state) => {
      return state.dailySummaries[0] || null
    },
    // 获取最新的每周摘要
    latestWeekly: (state) => {
      return state.weeklySummaries[0] || null
    },
    // 获取最新的每月摘要
    latestMonthly: (state) => {
      return state.monthlySummaries[0] || null
    },
  },
  actions: {
    // 获取每日摘要
    async fetchDailySummary(userId: number, date: string) {
      this.loading = true
      this.error = null
      try {
        console.log('[summaries] 获取每日摘要:', { userId, date })
        const res: any = await getDailySummary(userId, date)
        console.log('[summaries] 每日摘要响应:', res)
        
        const ok = res && (res.success === true || res.code === 0 || res.code === 200)
        if (!ok) throw new Error(res?.message || '获取每日摘要失败')
        
        const list = Array.isArray(res?.data?.list) ? res.data.list : []
        const mapped = list.map((item: any) => normalizeSummary({ ...item, type: 'daily' }))

        // 覆盖每日摘要列表（与后端返回一致顺序，最新在前）
        this.dailySummaries = mapped

        // 更新总列表
        mapped.forEach((s: Summary) => this.updateList(s))

        this.currentSummary = mapped[0] || null
        this.loaded = true
        
        return mapped
      } catch (e: any) {
        this.error = e?.message || '获取每日摘要失败'
        console.error('[summaries] 获取每日摘要失败:', e)
        throw e
      } finally {
        this.loading = false
      }
    },
    
    // 获取每周摘要
    async fetchWeeklySummary(userId: number, week: string) {
      this.loading = true
      this.error = null
      try {
        console.log('[summaries] 获取每周摘要:', { userId, week })
        const res: any = await getWeeklySummary(userId, week)
        console.log('[summaries] 每周摘要响应:', res)
        
        const ok = res && (res.success === true || res.code === 0 || res.code === 200)
        if (!ok) throw new Error(res?.message || '获取每周摘要失败')
        
        const list = Array.isArray(res?.data?.list) ? res.data.list : []
        const mapped = list.map((item: any) => normalizeSummary({ ...item, type: 'weekly' }))

        this.weeklySummaries = mapped
        mapped.forEach((s: Summary) => this.updateList(s))
        this.currentSummary = mapped[0] || null
        this.loaded = true
        
        return mapped
      } catch (e: any) {
        this.error = e?.message || '获取每周摘要失败'
        console.error('[summaries] 获取每周摘要失败:', e)
        throw e
      } finally {
        this.loading = false
      }
    },
    
    // 获取每月摘要
    async fetchMonthlySummary(userId: number, month: string) {
      this.loading = true
      this.error = null
      try {
        console.log('[summaries] 获取每月摘要:', { userId, month })
        const res: any = await getMonthlySummary(userId, month)
        console.log('[summaries] 每月摘要响应:', res)
        
        const ok = res && (res.success === true || res.code === 0 || res.code === 200)
        if (!ok) throw new Error(res?.message || '获取每月摘要失败')
        
        const list = Array.isArray(res?.data?.list) ? res.data.list : []
        const mapped = list.map((item: any) => normalizeSummary({ ...item, type: 'monthly' }))

        this.monthlySummaries = mapped
        mapped.forEach((s: Summary) => this.updateList(s))
        this.currentSummary = mapped[0] || null
        this.loaded = true
        
        return mapped
      } catch (e: any) {
        this.error = e?.message || '获取每月摘要失败'
        console.error('[summaries] 获取每月摘要失败:', e)
        throw e
      } finally {
        this.loading = false
      }
    },
    
    // 更新总列表
    updateList(summary: Summary) {
      const idx = this.list.findIndex(s => s.id === summary.id)
      if (idx >= 0) {
        this.list.splice(idx, 1, summary)
      } else {
        this.list.unshift(summary)
      }
      // 按创建时间降序排序
      this.list.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
    },
    
    // 清空当前摘要
    clearCurrent() {
      this.currentSummary = null
    },
    
    // 清空所有摘要
    clearAll() {
      this.list = []
      this.dailySummaries = []
      this.weeklySummaries = []
      this.monthlySummaries = []
      this.currentSummary = null
      this.loaded = false
      this.error = null
    },
  }
})
